import {
	defineStore
} from 'pinia';
import {
	computed,
	ref
} from 'vue';
export const useUserStore = defineStore('user', () => {
	// 收货地址
	const address = ref(JSON.parse(uni.getStorageSync("address") || "{}"))
	// 更新收货地址
	const updateAddress = nAddress => {
		address.value = nAddress
		saveAddressToLocal()
	}
	// 持久化收货地址
	const saveAddressToLocal = () => uni.setStorageSync("address", JSON.stringify(address.value))
	// 处理详细地址计算属性
	const addressStr = computed(() => {
		if (!address.value.provinceName) return ''
		return address.value.provinceName + address.value.cityName + address.value.countyName +
			address.value.detailInfo
	})
	// token
	const token = ref(uni.getStorageSync('token') || '')
	// 更新token
	const updateToken = nToken => {
		token.value = nToken
		saveToken2Local()
	}
	// 持久化token
	const saveToken2Local = () => uni.setStorageSync('token', token.value)
	// 用户信息
	const userInfoObj = ref(JSON.parse(uni.getStorageSync('userinfo') || '{}'))
	// 更新用户信息
	const updateUIO = nUIO => {
		userInfoObj.value = nUIO
		saveUIO2Local()
	}
	// 持久化用户信息
	const saveUIO2Local = () => uni.setStorageSync('userinfo', JSON.stringify(userInfoObj.value))
	// 重定向信息obj{openType,from}
	const backRedirectInfo = ref(null)
	// 更新重定向信息
	const updateBackRedirectInfo = from => (backRedirectInfo.value = from)
	return {
		address,
		updateAddress,
		addressStr,
		token,
		updateToken,
		userInfoObj,
		updateUIO,
		backRedirectInfo,
		updateBackRedirectInfo
	}
});